package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    // 菜品
    @Autowired
    private DishService dishService;
    // 菜品口味
    @Autowired
    private DishFlavorService dishFlavorService;
    // 分页对象
    @Autowired
    private CategoryService categoryService;
    //t套餐
    @Autowired
    private SetmealService setmealService;
    //套餐菜品
    @Autowired
    private SetmealDishService setmealDishService;
    //缓存管理
    private CacheManager cacheManager;

    /**
     * 停售菜品
     *
     * @param
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> updateWithStatus(@RequestParam List<Long> ids) {
        log.info("请求修改状态的id：{}", ids);
        //将ids封装进list集合
        List<Dish> dishList = dishService.listByIds(ids);
        //循环
        for (Dish dish : dishList) {
            //获取所有菜品id
            Long dishId = dish.getId();
            //套餐菜品的条件构造器
            LambdaQueryWrapper<SetmealDish> setmealDishWrapper = new LambdaQueryWrapper<>();
            setmealDishWrapper.eq(SetmealDish::getDishId, dishId);
            //将所有套餐菜品封装到集合中
            List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishWrapper);
            for (SetmealDish setmealDish : setmealDishList) {
                //获取套餐的id
                Long setmealId = setmealDish.getSetmealId();
                Setmeal setmeal = setmealService.getById(setmealId);
                if (setmeal.getStatus() == 1) {
                    setmeal.setStatus(0);
                    dish.setStatus(0);
                    dishService.updateById(dish);
                    setmealService.updateById(setmeal);
                }
                return R.success("停售菜品成功,相关联的套餐也已停售！");
            }
        }
        for (Dish dish : dishList) {
            dish.setStatus(0);
            dishService.updateById(dish);
        }
        return R.success("停售成功！");
    }

    /**
     * 起售菜品
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> updateStatu(@RequestParam List<Long> ids) {
        List<Dish> dishList = dishService.listByIds(ids);
        for (Dish dish : dishList) {
            dish.setStatus(1);
            dishService.updateById(dish);
        }
        return R.success("起售成功");
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    //删除数据库中数据的同时删除缓存中对应的数据
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("请求删除参数id:{}", ids);
        dishService.removeWithFlavor(ids);
        return R.success("删除成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    //第一次查询都去mysql数据库中查询并添加进redis缓存中，下次查询直接访问redis缓存
    @Cacheable(value = "dishCache", key = "'dish_'+ # dish.categoryId")
    public R<List<DishDto>> list(Dish dish) {
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询所有菜品
        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> dishDtoList = list.stream().map((item) -> {
            //创建菜品dto对象
            DishDto dishDto = new DishDto();
            //拷贝菜品数据
            BeanUtils.copyProperties(item, dishDto);
            //获取分类id
            Long categoryId = item.getCategoryId();
            //根据分类id获取分类对象
            Category category = categoryService.getById(categoryId);
            //判断当前分类是否为null，不为null，则赋值分类名称给dto
            if (category != null) {
                String name = category.getName();
                dishDto.setCategoryName(name);
            }
            //获取当前菜品id
            Long dishId = item.getId();
            //创建菜品口味条件构造器
            LambdaQueryWrapper<DishFlavor> dishFlavorWrapper = new LambdaQueryWrapper<>();
            //条件：查询菜品id
            dishFlavorWrapper.eq(DishFlavor::getDishId, dishId);
            //查询所有菜品口味
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorWrapper);
            //赋值给dto
            dishDto.setFlavors(dishFlavorList);
            //返回dto
            return dishDto;
        }).collect(Collectors.toList());
        //返回dto集合
        return R.success(dishDtoList);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    //
    @CacheEvict(value = "dishCache", key = "'dishDto_'+#dishDto.categoryId")
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 根据id查询菜品信息: 回显被修改的菜品数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 分页查询菜品信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        // 拼接分页查询的条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Dish::getName, name);
        // 分页查询
        dishService.page(pageInfo, wrapper);
        Page<DishDto> dishDtoPageInfo = new Page<>();
        // 完成对象中的数据拷贝, 参数1: 被拷贝的对象 参数2: 目标对象 参数3: 拷贝时忽略哪些字段不拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPageInfo, "records");
        // 获取当前页的记录
        List<Dish> dishList = pageInfo.getRecords();
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : dishList) {
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
//            DishDto dishDto = new DishDto();
//            dishDto.setName(dish.getName());
            // 将dish中的数据拷贝到dishdto中
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            // 封装分类的名称
            dishDto.setCategoryName(category.getName());
            dishDtoList.add(dishDto);
        }
        dishDtoPageInfo.setRecords(dishDtoList);
        return R.success(dishDtoPageInfo);
    }

    /**
     * 添加菜品信息
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("添加菜品携带的数据: {}", dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }
}    